

import SwiftUI
import TunnelKitManager
import NetworkExtension

struct ContentView: View {
    @State private var isChat  = false
    @State private var vpnConfigs: [VpnConfig] = []
    @State private var hasFetchedConfigs = false
    @State private var isList = false
    @State private var index = 1
    @StateObject private var vpnStatusManager = VPNStatusManager()
    @EnvironmentObject var speedViewModel: SpeedViewModel
    @EnvironmentObject var timerViewModdel: TimerViewModel
    private let vpn = NetworkExtensionVPN()
    @Binding var vpnStatus: Bool
    var body: some View {
        
        NavigationView {
            VStack(spacing: 0) {
               ZStack {
                    MainView()
                    VStack(spacing: 0) {
                    TopView()

                           statusImage(for: vpnStatusManager.vpnStatus)
                       
                        HStack {
                            Text("nation:")
                                .foregroundColor(.white)
                            
                            Text("QuickBooster \(index) ")
                                .foregroundColor(.white)
                            Image("flag")
                        }.onTapGesture {
                            self.isList = true
                        }
                        .onAppear{
                            let indx =  UserDefaultsManager.shared.getInt(forKey: "vpnList")
                            if indx == -1 {
                                self.index = 1
                            }else{
                                self.index = indx - 5
                            }
                        }.padding(.top,-10)
                      
                        
                        NavigationLink(destination: ListView(), isActive: $isList) {
                                        EmptyView()
                                    }
                                    .hidden()
                        Connecting(speedViewModel: speedViewModel,timerModel:timerViewModdel,vpnStatus:$vpnStatus)
                            .padding(.top,20)
                        
                        
                        BtnView()
                            .padding(.top,20)
                        
                        ZStack {
                            Image("girl")
                           
                                .cornerRadius(10)
                                .padding(.horizontal,20)
                            VStack{
                                Spacer()
                                Button(action: {
                                    self.isChat.toggle()
                                }) {
                                    
                                    Text("Chat")
                                        .foregroundColor(.black)
                                        .fontWeight(.bold)
                                        .frame(maxWidth: .infinity)
                                        .padding()
                                        .background(LinearGradient(gradient: Gradient(colors: [Color("connectStart"), Color("connectEnd")]),
                                                                   startPoint: .leading,
                                                                   endPoint: .trailing))
                                        .cornerRadius(10)
                                }
                                .padding(.horizontal,20)
                                .padding(.top,-20)
                            }
                        }
                        NavigationLink(destination: ModelList(), isActive: $isChat) {
                            EmptyView()
                        }.hidden()
                        
                        Spacer()
                    }
               }
            }
            .onAppear {
                     guard !hasFetchedConfigs else {
                         return
                     }
                     
                     hasFetchedConfigs = true
                     
                     NetworkManager().fetchVpnConfig { configs in
                         vpnConfigs = configs
                         print("Fetched \(configs.count) VPN configurations")
                         downloadAllVPNConfigs()
                     } failure: { error in
                         print("下载失败", error.localizedDescription)
                     }
                 }
            .navigationBarHidden(true)
            .navigationViewStyle(StackNavigationViewStyle())

            .navigationBarBackButtonHidden(true)
        }.navigationBarHidden(true)
            .navigationViewStyle(StackNavigationViewStyle())

            .navigationBarBackButtonHidden(true)
    }
    
    class Counter {
        var value = 1
        
        func currentValue() -> Int {
            return value
        }
    }


    let vpnConfigCounter = Counter()
    let vpnConfigQueue = DispatchQueue(label: "com.example.vpnConfigQueue")

    func downloadAllVPNConfigs() {
        for config in vpnConfigs {
            downloadVPNConfig(urlString: config.quickBoosterUrl)
        }
    }

    func downloadVPNConfig(urlString: String) {
        guard let url = URL(string: urlString) else {
            print("Invalid URL")
            return
        }

        let task = URLSession.shared.downloadTask(with: url) { localUrl, response, error in
            guard let localUrl = localUrl else {
                if let error = error {
                    print("Download failed: \(error.localizedDescription)")
                }
                return
            }
            
            do {
                var fileContents = try String(contentsOf: localUrl, encoding: .utf8)
                fileContents = fileContents.replacingOccurrences(of: "\r\n", with: "\n")
                fileContents = fileContents.replacingOccurrences(of: "\r", with: "\n")
                
                let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
                
                let newFileName = "hot\(vpnConfigCounter.currentValue()).ovpn"
                let savedUrl = documentsDirectory.appendingPathComponent(newFileName)
                
                try fileContents.write(to: savedUrl, atomically: true, encoding: .utf8)
                
                print("File downloaded, renamed, and moved to: \(savedUrl.path)")
                
                vpnConfigQueue.sync {
                    vpnConfigCounter.value += 1
                }
                
            } catch {
                print("File processing error: \(error.localizedDescription)")
            }
        }
        
        task.resume()
    }

    @ViewBuilder
       private func statusImage(for status: NEVPNStatus) -> some View {
           switch status {
           case .connected:
               Image("mainimg").resizable(resizingMode: .stretch).aspectRatio(contentMode: .fill)
                   .frame(width: 230,height: 230)
           case .disconnected:
               Image("close").resizable(resizingMode: .stretch).aspectRatio(contentMode: .fill)   .frame(width: 230,height: 230)
           case .connecting, .reasserting:
               Image("close").resizable(resizingMode: .stretch).aspectRatio(contentMode: .fill)   .frame(width: 230,height: 230)
           case .disconnecting:
               Image("close").resizable(resizingMode: .stretch).aspectRatio(contentMode: .fill)   .frame(width: 230,height: 230)
           default:
               Image("close").resizable(resizingMode: .stretch).aspectRatio(contentMode: .fill)   .frame(width: 230,height: 230)
           }
       }

}
//
//#Preview {
//    ContentView()
//}
struct TitleView: View {
    @State private var isSetting = false
    @State private var isUser = false
    
    
    var body: some View {
        HStack {
            Spacer()
            Text("Translate")
                .font(.title2)
                .fontWeight(.bold)
            Spacer()
            Image("user")
                .padding(.trailing, 20)
                .onTapGesture {
                    self.isUser.toggle()
                }
         
        }
    }
}

struct MainView: View {
    var body: some View {
        Rectangle()
            .foregroundColor(Color("mainback"))
            .edgesIgnoringSafeArea(.all)
    }
}

struct TopView: View {
    @State private var isList = false
    @State private var isContent = false
    var body: some View {
        HStack {
            Image("content")
                .resizable(resizingMode: .stretch)
                .aspectRatio(contentMode: .fill)
                .frame(width: 25,height: 25)
                .padding(.leading,20)
                .onTapGesture {
                    self.isContent = true
                }
            Spacer()
            Text("Home")
                .foregroundColor(.white)
                .font(/*@START_MENU_TOKEN@*/.title/*@END_MENU_TOKEN@*/)
            Spacer()
            Image("earch")
                .padding(.trailing,20)
                .onTapGesture {
                    self.isList = true
                }
            
            NavigationLink(destination: ListView(), isActive: $isList) {
                            EmptyView()
                        }
                        .hidden()
            
            NavigationLink(destination: SettingsView(), isActive: $isContent) {
                            EmptyView()
                        }
                        .hidden()
        }
    }
}



struct Connecting: View {
    @StateObject private var vpnStatusManager = VPNStatusManager()
    @State private var isConnecting = false
    var speedViewModel: SpeedViewModel
    var timerModel: TimerViewModel
    @State private var status = "connect"
    @Binding var vpnStatus: Bool
    var body: some View {
        VStack {
            Button(action: {
                handleVPNConnection { result in
                    switch result {
                    case .success(let connected):
                        if connected {
                            print("connect success")
                            isConnecting = true
                            timerModel.start()
                        } else {
                            isConnecting = false
                            timerModel.stop()
                        }
                    case .failure:
                        timerModel.stop()
                    }
                }
            }, label: {
                ZStack {
                    LinearGradient(gradient: Gradient(colors: [Color("connectStart"), Color("connectEnd")]),
                                   startPoint: .leading,
                                   endPoint: .trailing)
                    Text(buttonTitle)
                        .foregroundColor(.white)
                        .fontWeight(.bold)
                }
                .frame(width: UIScreen.main.bounds.width / 2.5, height: 50)
                .cornerRadius(25)
            })
            
            NavigationLink(destination: ResultView().environmentObject(speedViewModel)
                .environmentObject(timerModel), isActive: $isConnecting) {
                EmptyView()
            }
            .hidden()
        }.onAppear{
           
            if vpnStatus{
                
                status = buttonTitle
                print("qiantai")
                handleVPNConnections { result in
                    switch result {
                    case .success(let connected):
                        if connected {
                            print("connect success")
                            isConnecting = true
                            timerModel.start()
                        } else {
                            isConnecting = false
                            timerModel.stop()
                        }
                    case .failure:
                        timerModel.stop()
                    }
                }
            }
    
        }
    }

    private var buttonTitle: String {
        switch vpnStatusManager.vpnStatus {
        case .connected:
            return "Disconnect"
        case .connecting:
            return "Connecting"
        case .disconnected, .invalid, .disconnecting:
            return "Connect"
        default:
            return "Unknown"
        }
    }

    private func toggleVPNConnection() -> () -> Void {
        return {
            switch vpnStatusManager.vpnStatus {
            case .connected:
                VpnManager.shared.disconnect()
            case .disconnected, .invalid, .disconnecting:
                VpnManager.shared.connect()
            default:
                break
            }
        }
    }

    private func handleVPNConnection(completion: @escaping (Result<Bool, Error>) -> Void) {
        let toggleAction = toggleVPNConnection()
        toggleAction()
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
            switch vpnStatusManager.vpnStatus {
            case .connected:
                completion(.success(true))
            case .disconnected, .invalid, .disconnecting:
                completion(.success(false))
            default:
                completion(.failure(NSError(domain: "", code: -1, userInfo: nil)))
            }
        }
    }
    
    
    private func handleVPNConnections(completion: @escaping (Result<Bool, Error>) -> Void) {
    
        print("获得焦点执行")
        DispatchQueue.main.asyncAfter(deadline: .now() + 10) {
            switch vpnStatusManager.vpnStatus {
            case .connected:
                completion(.success(true))
            case .disconnected, .invalid, .disconnecting:
                completion(.success(false))
            default:
                completion(.failure(NSError(domain: "", code: -1, userInfo: nil)))
            }
        }
    }
}






struct BtnView: View {
    @State private var isChat = false
    @State private var isTranslate = false
    var body: some View {
        
        HStack {
            ZStack {
                
                Rectangle()
                
                    .fill(Color.gray)
                    .frame(width: UIScreen.main.bounds.width / 2.5 - 1, height: 70)
                    .cornerRadius(10)
                    .padding(.top,3)
                
                
                ZStack {
                    ZStack {
                        LinearGradient(gradient: Gradient(colors: [Color("btnEnd"), Color("btnStart")]),
                                       startPoint: .top,
                                       endPoint: .bottom)
                        
                        HStack {
                            Image("chat")
                            Text("Chat")
                                .foregroundColor(.white)
                                .fontWeight(.bold)
                        }.onTapGesture {
                            self.isChat.toggle()
                        }
                        
                    }
                    
                }  .frame(width: UIScreen.main.bounds.width / 2.5, height: 70)
                    .cornerRadius(10)
                
            }.padding(.leading,20)
            
            Spacer()
            
            ZStack {
                
                Rectangle()
                
                    .fill(Color.gray)
                    .frame(width: UIScreen.main.bounds.width / 2.5 - 1, height: 70)
                    .cornerRadius(10)
                    .padding(.top,3)
                
                
                ZStack {
                    ZStack {
                        LinearGradient(gradient: Gradient(colors: [Color("btnEnd"), Color("btnStart")]),
                                       startPoint: .top,
                                       endPoint: .bottom)
                        
                        HStack {
                            Image("tran")
                            Text("translate")
                                .foregroundColor(.white)
                                .fontWeight(.bold)
                        }.onTapGesture {
                            self.isTranslate.toggle()
                        }
                        
                        
                    }
                    NavigationLink(destination: ModelList(), isActive: $isChat) {
                        EmptyView()
                    }.hidden()
                    
                    NavigationLink(destination: TranslateView(), isActive: $isTranslate) {
                        EmptyView()
                    }.hidden()
                    
                    
                }  .frame(width: UIScreen.main.bounds.width / 2.5, height: 70)
                    .cornerRadius(10)
                
            }.padding(.trailing,20)
            
            
        }
    }
}
